import fetch from 'dva/fetch';
import qs from 'qs';
import { getToken } from "./authority"
import config from "../../config/config";
import { message } from 'antd'

function parseJSON(response) {
  return response.json();
}

function checkStatus(response) {
  if (response.status >= 200 && response.status < 300) {
    return response;
  }

  const error = new Error(response.statusText);
  error.response = response;
  throw error;
}

/**
 * Requests a URL, returning a promise.
 *
 * @param  {string} url       The URL we want to request
 * @param  {object} [options] The options we want to pass to "fetch"
 * @return {object}           An object containing either "data" or "err"
 */
export default function request(url, option) {
  const { method = '', ContentType = '' } = option || {}
  const options = {
    ...option,
  };
  const token = getToken();

  if (token) {
    options.headers = {
      'Authorization': token,
    };
  }
  if (method == 'POST') {
    if (ContentType && ContentType == 'multipart/form-data') {
      options.headers = {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Authorization': token
      }
      const {books} = option.body
      let data = []
      books.forEach((item,index) => {
        for (let i in item) {
          data.push({
            [`books[${index}].${i}`] : item[i]
          })
        }
      })
      delete option.body.books
      for (let i = 0; i < data.length; i++) {
        for (let key in data[i]) {
          option.body[key] = data[i][key]
        }
      }
      options.body = qs.stringify(option.body)
    } else {
      options.headers = {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Authorization': token
      }
      if (option.body) {
        options.body = qs.stringify(option.body)
      }
    }
  }
  return fetch(url, options)
    .then(checkStatus)
    .then(parseJSON)
    .then(data => {
      if (data.code == 20107) {
        message.destroy();
        message.error(data.msg)
        localStorage.getItem('token') && (setTimeout(() => {
          window.location.href = '/'
        }), 3000)
        localStorage.removeItem('token')
      }
      return ({ data })
    })
    .catch(err => ({ err }));
}
